const express = require('express');
const router = express.Router();
const db = require('../config/database');

router.get('/login', (req, res) => {
    res.render('login');
});

router.get('/register', (req, res) => {
    res.render('register');
});

// 验证规则
const validatePassword = (password) => {
    const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,20}$/;
    return regex.test(password);
};

const validateUsername = (username) => {
    const regex = /^[a-zA-Z0-9_]{4,16}$/;
    return regex.test(username);
};

router.post('/register', async (req, res) => {
    try {
        const { username, password } = req.body;

        if (!validateUsername(username)) {
            return res.render('register', {
                error: '用户名必须是4-16位的字母、数字或下划线'
            });
        }

        if (!validatePassword(password)) {
            return res.render('register', {
                error: '密码必须是8-20位，包含大小写字母、数字和特殊字符(!@#$%^&*)'
            });
        }

        await db.execute(
            'INSERT INTO users (username, password) VALUES (?, ?)',
            [username, password]
        );

        res.redirect('/login');
    } catch (error) {
        res.render('register', { error: '注册失败' });
    }
});

router.post('/login', async (req, res) => {
    try {
        const { username, password } = req.body;
        console.log('登录尝试:', { username, password });

        const [users] = await db.execute(
            'SELECT * FROM users WHERE username = ? AND password = ?',
            [username, password]
        );

        console.log('查询到的用户:', users);

        if (users.length > 0) {
            req.session.userId = users[0].id;
            console.log('登录成功，用户ID:', users[0].id);
            res.redirect('/todos');
        } else {
            console.log('登录失败：用户名或密码错误');
            res.render('login', { error: '用户名或密码错误' });
        }
    } catch (error) {
        console.error('登录错误:', error);
        res.render('login', { error: '登录失败' });
    }
});

router.get('/logout', (req, res) => {
    req.session.destroy();
    res.redirect('/login');
});

module.exports = router; 